package com.ts.service.achievement.impl;

import com.ts.dto.MemberDTO;
import com.ts.dto.OtherResearchDTO;
import com.ts.entity.Member;
import com.ts.entity.OtherResearch;
import com.ts.mapper.achievement.OtherResearchMapper;
import com.ts.mapper.achievement.OtherResearchMemberMapper;
import com.ts.service.achievement.OtherResearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
@Service
@Slf4j
public class OtherResearchServiceImpl implements OtherResearchService {
    @Autowired
    private OtherResearchMapper otherResearchMapper;

    @Autowired
    private OtherResearchMemberMapper otherResearchMemberMapper;

    /**
     * 保存其他研究
     */
    @Transactional
    @Override
    public Long save(OtherResearchDTO otherResearchDTO) {
        // 1.准备数据
        OtherResearch otherResearch = new OtherResearch();
        BeanUtils.copyProperties(otherResearchDTO, otherResearch);

        // 2.手动添加公共字段
        otherResearch.setCreateTime(LocalDateTime.now());
        otherResearch.setUpdateTime(LocalDateTime.now());
        otherResearch.setCreateBy(11L); // 实际项目中从登录用户获取
        otherResearch.setUpdateBy(11L);

        // 3.保存其他研究主表
        otherResearchMapper.save(otherResearch);

        // 4.处理成员信息
        saveMembers(otherResearchDTO.getMemberList(), otherResearch.getId());
        //返回id
        return otherResearch.getId();
    }

    /**
     * 根据ID查询研究详情
     */
    @Override
    public OtherResearchDTO getById(long id) {
        // 1.查询研究主表
        OtherResearch research = otherResearchMapper.getById(id);
        if (research == null) {
            return null;
        }

        // 2.转换为DTO
        OtherResearchDTO dto = new OtherResearchDTO();
        BeanUtils.copyProperties(research, dto);

        // 3.查询成员信息
        List<Member> members = otherResearchMemberMapper.getByResearchId(id);
        List<MemberDTO> memberDTOs = members.stream()
                .map(member -> {
                    MemberDTO memberDTO = new MemberDTO();
                    BeanUtils.copyProperties(member, memberDTO);
                    return memberDTO;
                })
                .collect(Collectors.toList());
        dto.setMemberList(memberDTOs);
        return dto;
    }

    /**
     * 更新其他研究
     */
    @Transactional
    @Override
    public void update(OtherResearchDTO otherResearchDTO) {
        // 0. 验证ID是否存在
        if (otherResearchDTO.getId() == null) {
            throw new RuntimeException("更新失败：ID不能为空");
        }
        // 1.准备数据
        OtherResearch otherResearch = new OtherResearch();
        BeanUtils.copyProperties(otherResearchDTO, otherResearch);

        // 2.设置更新信息
        otherResearch.setUpdateTime(LocalDateTime.now());
        otherResearch.setUpdateBy(11L); // 实际项目中从登录用户获取

        // 3.更新研究主表
        otherResearchMapper.update(otherResearch);

        // 4.更新成员信息：先删除后新增
        otherResearchMemberMapper.deleteByResearchId(otherResearch.getId());
        saveMembers(otherResearchDTO.getMemberList(), otherResearch.getId());
    }

    /**
     * 删除其他研究
     */
    @Transactional
    @Override
    public void delete(long id) {
        // 1.先删除成员信息（外键约束会自动删除，这里显式删除更清晰）
        otherResearchMemberMapper.deleteByResearchId(id);
        // 2.删除研究主表
        otherResearchMapper.delete(id);
    }

    /**
     * 保存成员信息
     */
    private void saveMembers(List<MemberDTO> memberList, Long researchId) {
        if (memberList != null && !memberList.isEmpty()) {
            List<Member> members = memberList.stream()
                    .map(memberDTO -> {
                        Member member = new Member();
                        BeanUtils.copyProperties(memberDTO, member);
                        member.setProjectId(researchId); // 设置关联的研究ID
                        return member;
                    })
                    .collect(Collectors.toList());
            otherResearchMemberMapper.batchInsert(members);
        }
    }
}
